import { defineStore } from "pinia";
import { User, RoleList } from "../types/user";
import { reqLogin } from "../api/login";
import { tip } from "../utils/alert";
import router from "../router";
import Cloud from "leancloud-storage";
import { reqEditManger } from "@/api/common";

interface loginType {
  mangerInfo: User | null;
}

export const useLoginStore = defineStore("login", {
  state: (): loginType => {
    return {
      mangerInfo: null
    };
  },
  actions: {
    mangerLogin(userInfo: { uid: string; password: string }) {
      const { uid, password } = userInfo;
      reqLogin({ uid, password })
        .then((res) => {
          console.log(res.data);
          if (res.data.code != 200) {
            tip(res.data.info, "error")
            return;
          } else {
            if (res.data.data.roleList) {
              this.mangerInfo = res.data.data;
              tip("登录成功", "success")
              router.push('/dataView')
            } else {
              tip("你不是管理员", "error")
            }

          }
        });
    },
    mangerLoginOut() {
      this.mangerInfo = null
      history.go(0)
    },
    async mangerEidt(baseInfo: User) {
      console.log(baseInfo.avatar != this.mangerInfo?.avatar);
      if (baseInfo.avatar != this.mangerInfo?.avatar) {
        let cloudFile = new Cloud.File("avtarImg", { base64: baseInfo.avatar });
        await cloudFile.save().then((res: any) => {
          baseInfo.avatar = res.attributes.url
        })
        this.mangerInfo = baseInfo
      }else{
        this.mangerInfo = baseInfo
      }
      
      await reqEditManger(this.mangerInfo).then(res => {
        if (res.data.code == 200) {
          tip(res.data.info, 'success')
        }
      })
    }
  },
  persist: [
    {
      paths: ["mangerInfo"],
      storage: localStorage,
    }
  ],
});
